package com.xbrother.lucene.store;

import com.xbrother.lucene.entity.LuceneIndexEntity;
import com.xbrother.lucene.service.LuceneIndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

/**
 * @author huangchangjin
 * @date 2025/5/13 19:31
 */
@Component
public class DatabaseIndexStore {
    @Autowired
    private LuceneIndexService luceneIndexService;

    // 假设数据库表结构为：file_name (主键), file_data (BLOB)
    public void writeFile(String fileName, byte[] data) {
        // 将数据写入数据库
        // INSERT INTO lucene_index (file_name, file_data) VALUES (?, ?)
        // ON DUPLICATE KEY UPDATE file_data = ?
        luceneIndexService.saveOrUpdate(new LuceneIndexEntity(fileName, data));
    }

    public byte[] readFile(String fileName) {
        // 从数据库读取数据
        // SELECT file_data FROM lucene_index WHERE file_name = ?
        LuceneIndexEntity lucene = luceneIndexService.getById(fileName);
        if (lucene != null) {
            return lucene.getFileData();
        }
        return new byte[0]; // 返回实际数据
    }

    public void deleteFile(String fileName) {
        // 删除数据库中的文件
        // DELETE FROM lucene_index WHERE file_name = ?
        luceneIndexService.removeById(fileName);
    }

    public String[] listAllFiles() {
        // 列出所有文件
        // SELECT file_name FROM lucene_index
        List<LuceneIndexEntity> list = luceneIndexService.list();
        return list.stream().map(LuceneIndexEntity::getFileName).toArray(String[]::new);
    }

    public void syncFiles(Collection<String> names) {
        // 同步文件到数据库
    }

    public void close() {
        // 关闭数据库连接
    }

    public long getFileLength(String name) {
        LuceneIndexEntity lucene = luceneIndexService.getById(name);
        if (lucene != null) {
            return lucene.getFileData().length;
        }
        return 0;
    }

    public void rename(String source, String dest) {
        LuceneIndexEntity lucene = luceneIndexService.getById(source);
        if (lucene != null) {
            luceneIndexService.removeById(source);
            lucene.setFileName(dest);
            luceneIndexService.saveOrUpdate(lucene);
        }
    }

    public boolean exists(String name) {
        LuceneIndexEntity lucene = luceneIndexService.getById(name);
        return lucene != null;
    }

    public String[] getPendingDeletions() {
        // todo
        return null;
    }

    public void syncFile(String name) {
        LuceneIndexEntity entity = luceneIndexService.getById(name);
        if (entity != null) {
            luceneIndexService.saveOrUpdate(entity);
        }
    }

    public void syncMetadata() {
        // todo
    }
}
